package com.example.zhengchaojun.arcgis.basicesTest;

import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.layers.Layer;
import com.example.zhengchaojun.arcgis.R;
import com.example.zhengchaojun.arcgis.basicesTest.adapter.LeandListviewAdapter;
import com.example.zhengchaojun.arcgis.listener.MapQueryOnTouchListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 类描述：查询要素
 * 作者：郑朝军 on 2018/5/10
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2018/5/10
 * 修改备注：
 */
public class QueryFeaturyActivity extends BaseMapActivity
{
    private ListView m_listView;
    private Spinner m_spinner;
    private View.OnTouchListener defauleOnTouchListener;//默认点击事件
    private MapQueryOnTouchListener mapQueryOnTouchListener;//要素选择事件

    public int getLayoutID()
    {
        return R.layout.activity_query_feature;
    }

    public void initView()
    {
        super.initView();
        m_mapViewDelegate.updateMagnifierWihtPanMapEnabled(true);
        m_listView = findViewById(R.id.listView);
        m_spinner = findViewById(R.id.spinnerView);
    }

    public void initData()
    {
        defauleOnTouchListener = m_mapView.getOnTouchListener();
        TextView textView = findViewById(R.id.tv_text);
        mapQueryOnTouchListener = new MapQueryOnTouchListener(this, m_mapView, textView, m_listView);
        if (mapQueryOnTouchListener != null)
        {
            super.m_mapView.setOnTouchListener(mapQueryOnTouchListener);
        }
        mapQueryOnTouchListener.clear();//清空当前选择

        // spinner控件
        LeandListviewAdapter adapter3 = new LeandListviewAdapter(this, m_mapView.getMap().getOperationalLayers());
        m_spinner.setAdapter(adapter3);
    }

    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.cx:
                doClickSpinner();
                break;
        }
    }

    private void doClickSpinner()
    {
        Layer layer = (Layer) m_spinner.getSelectedItem();
        if (layer != null)
        {
            String search = ((TextView) findViewById(R.id.edit_query)).getText().toString();
            queryAttrubute((FeatureLayer) layer, search);
        }
    }

    private void queryAttrubute(FeatureLayer layer, String search)
    {
        QueryParameters queryParameters = new QueryParameters();
        String whereStr = GetWhereStrFunction(layer, search);
        queryParameters.setWhereClause(whereStr);
        final ListenableFuture<FeatureQueryResult> featureQueryResult = layer.getFeatureTable().queryFeaturesAsync(queryParameters);
        featureQueryResult.addDoneListener(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    List<Feature> mapQueryResult = new ArrayList<>();//查询统计结果

                    FeatureQueryResult result = featureQueryResult.get();
                    Iterator<Feature> iterator = result.iterator();
                    Feature feature;
                    while (iterator.hasNext())
                    {
                        feature = iterator.next();
                        mapQueryResult.add(feature);
                    }

                    showShort("查询出" + mapQueryResult.size() + "个符合要求的结果");
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    public void showShort(String text)
    {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取模糊查询字符串
     *
     * @param featureLayer
     * @param search
     * @return
     */
    private String GetWhereStrFunction(FeatureLayer featureLayer, String search)
    {
        StringBuilder stringBuilder = new StringBuilder();
        List<Field> fields = featureLayer.getFeatureTable().getFields();
        boolean isNumber = isNumberFunction(search);
        for (Field field : fields)
        {
            switch (field.getFieldType())
            {
                case TEXT:
                    stringBuilder.append(" upper(");
                    stringBuilder.append(field.getName());
                    stringBuilder.append(") LIKE '%");
                    stringBuilder.append(search.toUpperCase());
                    stringBuilder.append("%' or");
                    break;
                case SHORT:
                case INTEGER:
                case FLOAT:
                case DOUBLE:
                case OID:
                    if (isNumber == true)
                    {
                        stringBuilder.append(" upper(");
                        stringBuilder.append(field.getName());
                        stringBuilder.append(") = ");
                        stringBuilder.append(search);
                        stringBuilder.append(" or");
                    }
                    break;
                case UNKNOWN:
                case GLOBALID:
                case BLOB:
                case GEOMETRY:
                case RASTER:
                case XML:
                case GUID:
                case DATE:
                    break;
            }
        }
        String result = stringBuilder.toString();
        return result.substring(0, result.length() - 2);
    }

    /**
     * 判断是否为数字
     *
     * @param string
     * @return
     */
    public boolean isNumberFunction(String string)
    {
        boolean result = false;
        Pattern pattern = Pattern.compile("^[-+]?[0-9]");
        if (pattern.matcher(string).matches())
        {
            //数字
            result = true;
        }
        else
        {
            //非数字
        }
        //带小数的
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append('^');
        stringBuilder.append('[');
        stringBuilder.append("-+");
        stringBuilder.append("]?[");
        stringBuilder.append("0-9]+(");
        stringBuilder.append('\\');
        stringBuilder.append(".[0-9");
        stringBuilder.append("]+)");
        stringBuilder.append("?$");
        Pattern pattern1 = Pattern.compile(stringBuilder.toString());
        if (pattern1.matcher(string).matches())
        {
            //数字
            result = true;
        }
        else
        {
            //非数字
        }
        return result;
    }

}
